package com.jcl.tree.utils;

import lombok.Data;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2021/3/17 21:00
 */
public class BuildTest
{
    public static void main(String[] args) {
        ArrayList<Person> people = new ArrayList<>();
        Person p1 = new Person();
        p1.setId(1);
        p1.setName("张三");
        p1.setClazz("一班");
        people.add(p1);

        Person p2 = new Person();
        p2.setId(2);
        p2.setName("张三");
        p2.setClazz("二班");
        people.add(p2);

        Person p3 = new Person();
        p3.setId(3);
        p3.setName("李四");
        p3.setClazz("三班");
        people.add(p3);

        Person p4 = new Person();
        p4.setId(4);
        p4.setName("李四");
        p4.setClazz("四班");
        people.add(p4);
        System.out.println(people);

        ArrayList<HashMap<String, Object>> maps = new ArrayList<>();

        callMethod(people,0,maps);
        System.out.println(maps);
    }

    public static void callMethod(ArrayList<Person> list, Integer i, ArrayList<HashMap<String, Object>> list2){
//        System.out.println("list"+ list2);
        if (list.size() == i){
            return;
        }
        if (list2 == null) {
            return;
        }
        Person person = list.get(i);
        String name = person.getName();
        String clazz = person.getClazz();
        Integer id = person.getId();
        boolean flag = true;
        if (list2.size() > 0){
            for (HashMap<String, Object> map : list2){
                String n1 = map.get("name").toString();
                ArrayList<HashMap<String, Object>> children = (ArrayList<HashMap<String, Object>>)map.get("children");
                if (n1.equals(name)){
                    // 存在
                    HashMap<String, Object> map1 = new HashMap<>();
                    map1.put("class",clazz);
                    map1.put("id",id);
                    children.add(map1);
                    flag = false;
                    break;
                }
            }
        }
        if (flag){
            // 没有这个key 进行创建
            HashMap<String, Object> map = new HashMap<>();
            list2.add(map);
            map.put("name", name);
            ArrayList<HashMap<String, Object>> children = new  ArrayList<HashMap<String, Object>>();
            HashMap<String, Object> map1 = new HashMap<>();
            map1.put("id",id);
            map1.put("class", clazz);
            children.add(map1);
            map.put("children",children);
        }
        i++;
        callMethod(list, i, list2);
    }
}

@Data
class Person{
    private Integer id;
    private String name;
    private String clazz;
}
